// 地理编码与逆地理编码
// hooks/useGeocoder.ts
import { useState } from 'react';

export const useGeocoder = () => {
  const [geocoder] = useState(new AMap.Geocoder());

  const geocode = async (address: string): Promise<AMap.LngLat> => {
    return new Promise((resolve, reject) => {
      geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.geocodes.length > 0) {
          resolve(result.geocodes[0].location);
        } else {
          reject(new Error('地理编码失败'));
        }
      });
    });
  };

  const reverseGeocode = async (lnglat: AMap.LngLat): Promise<string> => {
    return new Promise((resolve, reject) => {
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          resolve(result.regeocode.formattedAddress);
        } else {
          reject(new Error('逆地理编码失败'));
        }
      });
    });
  };

  return { geocode, reverseGeocode };
};